/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */

var diameterOfBinaryTree = function (root) {
    let maxDiameter = 0;

    function getHeight(node) {
        if (node === null) return 0;
        let left = getHeight(node.left);
        let right = getHeight(node.right);
        // 每个节点都尝试作为路径的中点，更新最大直径
        maxDiameter = Math.max(maxDiameter, left + right);
        return Math.max(left, right) + 1;
    }

    getHeight(root);
    return maxDiameter;
};